from multiprocessing import Process, Pipe
import time


def pipe_SendData(pipe):
    data_list = [1, 2, 3, 4, 5, "abc", "def"]
    for data in data_list:
        pipe.send(data)
        print("child process: send data: ", data)
        time.sleep(1)
    pipe.close()


if __name__ == "__main__":
    parent_pip, child_pip = Pipe()
    child_process = Process(target=pipe_SendData, args=(child_pip,))
    child_process.start()
    while True:
        try:
            # 使用poll()检查是否有数据可读，避免阻塞
            if parent_pip.poll():
                print("parent process: recv data: ", parent_pip.recv())
            else:
                # 如果没有数据可读，检查子进程是否还在运行
                if not child_process.is_alive():
                    print("子进程已退出")
                    break
                time.sleep(1)  # 短暂休眠避免CPU占用过高
        except EOFError:
            print("Pipe已关闭")
            break
        except Exception as e:
            print("发生错误:", e)
            break
    parent_pip.close()
    child_pip.close()
    child_process.join()
